package com.uchedao.seller.manager;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.uchedao.seller.SellerApplication;
import com.uchedao.seller.config.Api;
import com.uchedao.seller.http.request.HttpRequest;
import com.uchedao.seller.http.VolleyUtil;
import com.uchedao.seller.http.entity.TokenEntity;
import com.uchedao.seller.util.LogUtil;
import com.uchedao.seller.util.PreferenceUitl;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by hang on 2015/9/17.
 */
public class AppInfoManager {

    private static String KEY_TOKEN = "token";
    private static String KEY_DB = "database";
    private static String BLUETOOTH_NAME = "bluetooth_name";
    private static String BLUETOOTH_ADDRESS = "bluetooth_address";

    public static class Info {
        public static String APP_ID = "18ff43a603f88559";
        public static String APP_SECRET = "7ea915c9a939af4d63ef362ebaf123d0";
    }

    private static PreferenceUitl pref = new PreferenceUitl(SellerApplication.getContext(), "uchedao", Context.MODE_PRIVATE);

    public static void saveToken(String token) {
        pref.putString(KEY_TOKEN, token);
    }

    public static String getToken() {
        return pref.getString(KEY_TOKEN);
    }

    public static void saveDB(boolean state) {
        pref.putBoolean(KEY_DB, state);
    }

    public static boolean getDB() {
        return pref.getBoolean(KEY_DB, false);
    }

    public static void setBluetoothAddress(String address) {
        pref.putString(BLUETOOTH_ADDRESS, address);
    }

    public static String getBluetoothAddress() {
        return pref.getString(BLUETOOTH_ADDRESS);
    }

    public static void setBluetoothName(String name) {
        pref.putString(BLUETOOTH_NAME, name);
    }

    public static String getBluetoothName() {
        return pref.getString(BLUETOOTH_NAME);
    }

    /**
     * 获取token
     */
    public static void syncToken() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("appid", Info.APP_ID);
        map.put("secret", Info.APP_SECRET);
        Request req = HttpRequest.getRequest(HttpRequest.GET, Api.Action.TOKEN, map,
                new Response.Listener<JsonObject>() {
                    @Override
                    public void onResponse(JsonObject response) {
                        TokenEntity entity = new Gson().fromJson(response, TokenEntity.class);
                        saveToken(entity.getToken());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        LogUtil.e(error.getMessage());
                    }
                });
        VolleyUtil.getInstance().getRequestQueue().add(req);
    }

}
